package cn.dankal.flyaudio.home

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import api.HomeServiceFactory
import cn.dankal.basiclib.base.callback.DKCallBackObject
import cn.dankal.basiclib.base.fragment.BaseStateFragment
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.rx.AbstractStateSubscriber
import cn.dankal.basiclib.util.TimeUtil
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.business.Constants
import cn.dankal.business.pojo.ActivityBean
import cn.dankal.business.pojo.CurrentBean
import cn.dankal.business.pojo.HomeBean
import cn.dankal.flyaudio.EyeFragment
import cn.dankal.flyaudio.R
import com.alibaba.android.arouter.launcher.ARouter
import com.yzq.zxinglibrary.android.CaptureActivity
import kotlinx.android.synthetic.main.fragement_home.*
import kotlinx.android.synthetic.main.layout_scanner_title.*
import kotlinx.android.synthetic.main.rv_item_information.view.*

class HomeFragment : BaseStateFragment(), CurrentAdapter.OnPraiseListener, PraiseHelper.PraiseCallback {

    override fun deleteDate(uuids: Any, position: Int) {
    }

    var activityAdapter = ActivityAdapter()
    var currentAdapter = CurrentAdapter(DKCallBackObject {})
    var parisePresenter = PraiseHelper()

    override fun contentView(): Any {
        return swipe_toload_layout
    }

    override fun initComponents() {
        setTranslucent(activity, ll_scan_title)
        tv_activity_more.setOnClickListener {
            (parentFragment as EyeFragment).select(Constants.ITEM_ACTIVITY)
//            (activity as TabMainActivity).select(Constants.ITEM_ACTIVITY)
        }
        tv_information_more.setOnClickListener {
            (parentFragment as EyeFragment).select(Constants.ITEM_INFORMATION)
        }
        tv_current_more.setOnClickListener {
            (parentFragment as EyeFragment).select(Constants.ITEM_CURRENT)
        }

        rv_home_activity.adapter = activityAdapter
        rv_home_activity.layoutManager = LinearLayoutManager(context, LinearLayout.HORIZONTAL, false)
        swipe_toload_layout?.setOnRefreshListener {
            obtainData()
        }
        iv_scan.setOnClickListener {

            activity?.startActivityForResult(Intent(context, CaptureActivity::class.java), Constants.SCAN)
        }
        currentAdapter.setOnParseListener(this)
        recycle_current_container.adapter = currentAdapter
        recycle_current_container.layoutManager = LinearLayoutManager(context)
        // 解决双 recycleView 滑动卡顿问题
        recycle_current_container.isNestedScrollingEnabled = false

    }

    private var isCreated = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isCreated=true
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (!isCreated) {
            return
        }

        if (isVisibleToUser) {
            obtainData()
        }
    }

    override fun obtainData() {
        HomeServiceFactory.info_list("1", "3")
                .subscribe(object : AbstractStateSubscriber<HomeBean>(this) {
                    override fun onNext(t: HomeBean) {
                        super.onNext(t)
                        setData(t)
                        isCreate = false
                        isHasLoadOnce = true
                    }
                })
        swipe_toload_layout?.isRefreshing = false
    }

    private fun setData(t: HomeBean) {
        ll_information_container.removeAllViews()

        //添加活动
        addActivity(t)
        //资讯推荐
        addInfo(t)
        //此刻推荐
        addCurrent(t)
    }

    private fun addActivity(t: HomeBean) {
        if (t.vehicleActivityVOList.isEmpty()) {
            ll_activity.visibility = View.GONE
        } else {
            ll_activity.visibility = View.VISIBLE
            activityAdapter.setOnRvItemClickListener(object : OnRvItemClickListener<ActivityBean>() {
                override fun onItemClick(v: View?, position: Int, data: ActivityBean) {
                    ARouter.getInstance().build(MainProtocol.ACTIVITY_DETAIL)
                            .withString(Constants.UUID, data.uuid)
                            .navigation()
                }
            })
            //活动
            activityAdapter.updateData(t.vehicleActivityVOList)
        }
    }

    private fun addInfo(t: HomeBean) {
        ll_information.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
            }
        })

        if (t.vehicleInfoVOList.isEmpty()) {
            ll_information.visibility = View.GONE
        } else {
            ll_information.visibility = View.VISIBLE
            t.vehicleInfoVOList[0].apply {
                PicUtils.loadRoundPic(context, cover, iv_information_img, PicUtils
                        .DEFAULT_ROUND_RADIUS, R.mipmap
                        .pic_banner_holder, R.mipmap.pic_banner_holder)
                tv_information_title.setText(title)
                tv_information_time.text = TimeUtil.getFgtime(createTime)
                tv_information_comment_count.text = commentNumber
                tv_information_view_count.text = lookNumber
                cl_information.setOnClickListener {
                    ARouter.getInstance().build(MainProtocol.INFO_DETAIL)
                            .withString(Constants.UUID, this.uuid)
                            .navigation()
                }
            }

            for (i in 1..t.vehicleInfoVOList.size - 1) {
                //资讯
                var informationView = layoutInflater.inflate(R.layout.rv_item_information, null)
                //   t.vehicleInfoVOList
                var infoBean = t.vehicleInfoVOList[i]
                infoBean?.apply {
                    PicUtils.loadRoundPic(context,cover, informationView.findViewById(R.id.iv_img))
                    informationView.findViewById<TextView>(R.id.tv_title).setText(title)
                    informationView.findViewById<TextView>(R.id.tv_time).setText(TimeUtil.getFgtime(createTime))
                    informationView.findViewById<TextView>(R.id.tv_comment_count).text = commentNumber
                    informationView.tv_view_count.setText(lookNumber)
                }
                informationView.setOnClickListener {
                    ARouter.getInstance().build(MainProtocol.INFO_DETAIL)
                            .withString(Constants.UUID, infoBean.uuid)
                            .navigation()
                }

                ll_information_container.addView(informationView)
            }
        }
    }

    private fun addCurrent(t: HomeBean) {
        if (t.userInfoVOList.isEmpty()) {
            ll_current.visibility = View.GONE
        } else {
            ll_current.visibility = View.VISIBLE
        }
        currentAdapter.updateData(t.userInfoVOList)
        currentAdapter.setOnRvItemClickListener(object : OnRvItemClickListener<CurrentBean>() {
            override fun onItemClick(v: View?, position: Int, data: CurrentBean) {
                ARouter.getInstance().build(MainProtocol.CURRENT_DETAIL)
                        .withString(Constants.UUID, data.uuid)
                        .navigation()
            }
        })
    }

    override fun praise(uuid: String, type: String, position: Int) {
        var likeCount = currentAdapter.datas.get(position).likeNumber.toInt()
        currentAdapter.datas.get(position).likeNumber = likeCount.inc().toString()
        currentAdapter.datas.get(position).isPraise = 1
        currentAdapter.notifyItemChanged(position, "star")

        ToastUtils.showShort("点赞成功")
        parisePresenter.praise(position, 1, uuid, this)
    }

    override fun praiseCancel(uuid: String, type: String, position: Int) {
        var likeCount = currentAdapter.datas.get(position).likeNumber.toInt()
        currentAdapter.datas.get(position).likeNumber = likeCount.dec().toString()
        currentAdapter.datas.get(position).isPraise = 0
        currentAdapter.notifyItemChanged(position, "star")

        ToastUtils.showShort("点赞取消")
        parisePresenter.praiseCancel(position, 1, uuid, this)
    }

    override fun onPraiseSuccess(position: Int, isPraise: Boolean) {
        /*  var likeCount = currentAdapter.datas.get(position).likeNumber.toInt()
          if (isPraise) {
              currentAdapter.datas.get(position).likeNumber = likeCount.dec().toString()
              currentAdapter.datas.get(position).isPraise = 0
          } else {
              currentAdapter.datas.get(position).likeNumber = likeCount.inc().toString()
              currentAdapter.datas.get(position).isPraise = 1
          }
          currentAdapter.notifyItemChanged(position, "star")*/
    }

    override fun onPraiseFailure(position: Int, errorInfo: String?) {}

    companion object {

        fun newInstance(): HomeFragment {
            val fragment = HomeFragment()
            return fragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragement_home
    }


}
